package com.boot.weirdor.web.www;

import com.boot.weirdor.common.enums.EnumSvrResult;
import com.boot.weirdor.web.base.BaseController;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by weirdor on 2017/8/3.
 */
@Controller
@RequestMapping("/api")
public class LoginController  extends BaseController{
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);


    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView login(ModelAndView modelAndView) {
        modelAndView.setViewName("login/login");
        return modelAndView;
    }

    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Object login(HttpServletRequest request, @RequestParam(value = "username")  String username,
                                     @RequestParam(value = "password") String password, @RequestParam(value = "verify")String verify) {

        Map<String, Object> map = new HashMap<String, Object>();
        System.out.println("username:" + username + "----" + "password:" + password);
        String verifyCode = String.valueOf(request.getSession().getAttribute("verify"));
        System.out.println(verify+"-------"+verifyCode);

        if (!verifyCode.toLowerCase().equalsIgnoreCase(verify.toLowerCase())) {
            map.put("code", "400");
            map.put("msg", "验证码错误");
            return map;
        }
        request.getSession().removeAttribute("verify");
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);
            // 验证是否登录成功
            if (subject.isAuthenticated()) {
                request.getSession().setAttribute("username", username);
                System.out.println("用户[" + username + "]登录认证通过(这里可以进行一些认证通过后的一些系统参数初始化操作)");
                map.put("code", 200);
                map.put("msg", "登录成功");
                System.out.println(request.getSession().getAttribute("username"));
            } else {
                token.clear();
            }
        } catch (UnknownAccountException e) {
            map.put("code", 400);
            map.put("msg", "用户名不存在");
            logger.info("用户名不存在");
        } catch (IncorrectCredentialsException e) {
            map.put("code", 400);
            map.put("msg", EnumSvrResult.ERROR_ACCOUNT_PASSWORD_ERROR.getName());
            logger.info("用户名/密码错误");
        } catch (ExcessiveAttemptsException e) {
            map.put("code", 400);
            map.put("msg", "登录失败多次，账户锁定10分钟");
            // TODO: handle exception
            logger.info("登录失败多次，账户锁定10分钟");
        }
        catch(LockedAccountException e){
            map.put("code", 400);
            map.put("msg", "账户被锁定");
            // 其他错误，比如锁定，如果想单独处理请单独catch处理
            logger.info("账户被锁定");
        }
        catch (AuthenticationException e) {
            map.put("code", 400);
            map.put("msg", "其他错误");
            // 其他错误，比如锁定，如果想单独处理请单独catch处理
            logger.info("其他错误：" + e.getMessage());
        }
        return map;
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            subject.logout(); // session 会销毁，在SessionListener监听session销毁，清理权限缓存
            if (logger.isDebugEnabled()) {
                System.out.println("用户退出");
            }
        }
        return "redirect:/admin/login";
    }
}

